package com.java.socket.tcp.multiclient.whileloop.client;

import java.io.*;
import java.net.Socket;

/**
 * 多客户端Socket情况下的Socket客户端(和但客户端没有区别，有区别的是服务端)
 *
 * @author xzmeasy
 * @version 1.0
 * @since 星期一 十二月,2018
 */
@SuppressWarnings("Duplicates")
public class ClientSocketExample {

    public static void main(String[] args) {
        try {
            // 创建客户端Socket，链接到指定ip和端口的服务端
            Socket socket = new Socket("localhost", 8888);


            // 创建输出流并发送消息到服务端
            OutputStream outputStream = socket.getOutputStream();
            PrintWriter printWriter = new PrintWriter(outputStream);
            String message = "来自客户端的消息";
            printWriter.write(message);
            printWriter.flush();
            // 此处不能漏
            socket.shutdownOutput();


            // 创建输入流并接收从服务端发送过来的反馈信息
            InputStream inputStream = socket.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String temp = null;
            StringBuffer info = new StringBuffer();
            while ((temp = bufferedReader.readLine()) != null) {
                info.append(temp);
            }
            System.out.println("来自服务端的反馈信息: " + info.toString());


            // 关闭资源
            bufferedReader.close();
            inputStreamReader.close();
            inputStream.close();
            printWriter.close();
            outputStream.close();
            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
